package com.google.qam.texture;

import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.SparseArray;

public final class ResourceTexture extends Texture {
	private static final SparseArray<ResourceTexture> cache = new SparseArray<ResourceTexture>();
	
	private final int mResourceId;
    private final boolean mScaled;
	
    public static ResourceTexture createResourceTexture(int resourceId){
    	return createResourceTexture(resourceId, true);
    }
    
    public static ResourceTexture createResourceTexture(int resourceId, boolean scaled){
    	ResourceTexture texture = cache.get(resourceId);
    	if (texture == null && resourceId != 0) {
    		texture = new ResourceTexture(resourceId, scaled);
    		cache.put(resourceId, texture);
    	}
    	return texture;
    }
    
    private ResourceTexture(int resourceId, boolean scaled) {
        mResourceId = resourceId;
        mScaled = scaled;
    }
    
	@Override
	public Bitmap load(Context context) {
		if(mState == STATE_UNLOADED) {
			mState = STATE_LOADED;
			loadTextureAsync(context);
		}
		return mBitmap;
	}
	
	private void loadTextureAsync(Context context) {
		// Load a bitmap from the resource.
		Bitmap bitmap = null;
        if (mScaled) {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
            bitmap = BitmapFactory.decodeResource(context.getResources(), mResourceId, options);
        } else {
            InputStream inputStream = context.getResources().openRawResource(mResourceId);
            if (inputStream != null) {
                try {
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                    bitmap = BitmapFactory.decodeStream(inputStream, null, options);
                } catch (Exception e) {
                } finally {
                    try {
                        inputStream.close();
                    } catch (IOException e) { /* ignore */
                    }
                }
            }
        }
        
        mBitmap = bitmap;
	}
}
